//
//  ViewController.m
//  socket的通信过程
//
//  Created by 伍银荣 on 2021/9/2.
//  Copyright © 2021 com.WYR. All rights reserved.
//

#import "ViewController.h"
#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //1.创建socket
    /**
     * 参数1:domin  协议域 AF_INET-----IPV4
     * 参数2:type  socket类型  SOCK_STREAM(TCP)   SOCK_DGRAM(UDP)
     * 参数3: protocol协议,  IPPROTO_TCP(TCP)    IPPROTO_UDP(UDP) ,如果传入0,会根据第二个参数选择合适的值
     * 返回值: >0 ,表示创建成功,  socket的描述符  -1表示创建失败
     */
    //SOCK_STREAM:TCP协议
    int clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    //2.连接到服务器
    /**
     * 第一个参数:socket的描述符
     * 第二个参数:结构体 IP地址和端口
     * 第三个参数: 结构体的长度  sizeof()
     * 返回值:成功0,失败非0
     */
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    addr.sin_port = htons(12345);
    int result = connect(clientSocket, (const struct sockaddr *)&addr, sizeof(addr));
    if (result != 0) {
        NSLog(@"连接失败");
        return;
    }
    //3.向服务器发送数据
    //成功:则返回实际发送过去的字符数,失败为-1
    const char *msg = "hello world";
    ssize_t sendCount = send(clientSocket, msg, strlen(msg), 0);
    NSLog(@"发送的字节数:%zd",sendCount);
    //4.从服务器接收数据
    uint8_t buffer[1024];
    ssize_t recvCount = recv(clientSocket, buffer, sizeof(buffer), 0);
    NSLog(@"接收的字节数:%zd",recvCount);
    
    //把字节数组转化成字符串
    NSData *data = [[NSData alloc]initWithBytes:buffer length:recvCount];
    NSString *msgStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"收到字符串:%@",msgStr);
    
    //5.关闭连接
    close(clientSocket);
}


@end
